Skip to main content

Debug in JavaScrip

· One min read

debugger

In browser, debugger can trigger breakpoint

debugger;

Debug native function

function debug(fn) {
return function () {
debugger;
return fn.apply(this, arguments);
};
}

To debug "string".at()

String.prototype.at = debug(String.prototype.at);

To debug console.log()

console.log = debug(console.log);

Inject function

function inject(to, fn) {
return function () {
fn.apply(this, arguments);
return to.apply(this, arguments);
};
}

To log the call stack and arguments when "string".replace() is called

String.prototype.replace = inject(
String.prototype.replace,
function () {
console.trace();
console.log(arguments);
}
);

"abc".replace("a", "s");

Call stack trace

Get the call stack

new Error().stack

Print the call stack

console.trace();

console.trace("message");

Debug in node.js

node --inspect server.js